<template>
  <div class="analysis">
    <div class="filter-wrap">
      <div class="filter-title">{{ $t("form.statistics.filterData") }}</div>
      <div class="filter-header">
        <div class="left">
          <el-input
            prefix-icon="ele-Search"
            size="default"
            clearable
            :placeholder="$t('form.formData.fullTextSearch')"
            style="width: 200px"
            v-model="inputSearch"
          />
          <el-date-picker
            class="ml20"
            size="default"
            v-model="dataFilterDateRange"
            type="datetimerange"
            :range-separator="$t('form.statistics.to')"
            :start-placeholder="$t('form.statistics.startTime')"
            :end-placeholder="$t('form.statistics.endTime')"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </div>
        <div class="right">
          <el-button
            class="ml20"
            size="default"
            @click="handleReset()"
          >
            {{ $t("form.statistics.reset") }}
          </el-button>
          <el-button
            class="ml10"
            size="default"
            type="primary"
            @click="handleFilter()"
          >
            {{ $t("form.statistics.filter") }}
          </el-button>
          <el-link
            class="ml20"
            type="primary"
            :underline="false"
            @click="isExpand = !isExpand"
            :icon="isExpand ? 'ele-ArrowUp' : 'ele-ArrowDown'"
          >
            {{ $t("form.statistics.expand") }}
          </el-link>
        </div>
      </div>
      <data-filter
        class="w100"
        v-if="isExpand"
        :fields="fields"
        :form-data-filter="dataFilterParams.filter"
        @filter="val => (dataFilterParams.filter = val)"
      />
    </div>

    <div class="chart-container" v-if="list.length && list.length !== 0">
      <div
        v-for="(item, index) in list"
        :key="index"
        class="chart-item"
      >
        <el-card class="chart-card" shadow="hover">
          <div class="title-wrap">
            <div class="title">
              <span class="question-number">Q{{ index + 1 }}</span>
              {{ item.label }}（{{ item.type }}）
            </div>
            <el-segmented
              v-model="item.chartType"
              :options="options"
              size="default"
              class="chart-type-btn"
            />
          </div>
          <el-row :gutter="20">
            <el-col :span="12">
              <t-chart
                :option="getCharData(item)"
                :init-options="initOptions"
                theme="tduck-echarts-theme"
                class="chart"
              />
            </el-col>
            <el-col :span="12">
              <div class="table-container">
                <div class="analysis-table-title">{{ $t("form.statistics.proportion") }}</div>
                <el-table
                  :data="getTableData(item)"
                  height="350"
                  style="width: 100%"
                  :header-cell-style="{ background: 'var(--el-fill-color-light)' }"
                  border
                >
                  <el-table-column
                    prop="fieldName"
                    sortable
                    :label="$t('form.statistics.label')"
                    width="280"
                  ></el-table-column>
                  <el-table-column
                    prop="data"
                    sortable
                    :label="$t('form.statistics.totalCount')"
                    width="280"
                  ></el-table-column>
                  <el-table-column
                    prop="proportion"
                    sortable
                    :label="$t('form.statistics.proportion')"
                    width="280"
                  ></el-table-column>
                </el-table>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </div>
    </div>
    <el-empty
      v-else
      :description="$t('form.statistics.onlyChartAvailable')"
    />
  </div>
</template>

<script setup name="Analysis">
import { onMounted, ref } from "vue";
import { getFormAnalysisRequest } from "@/api/project/report";
import { i18n } from "@/i18n";
import { useRoute } from "vue-router";
import TChart from "@/views/components/TChart/index.vue";
import DataFilter from "@/views/form/data/filter/index.vue";
import { listFormFieldsRequest } from "@/api/project/form";
import { cloneDeep } from "lodash-es";
import { chartOptionMap } from "@/views/form/statistics/analysis/chartOptionData";

const initOptions = ref({
  renderer: "png"
});

const list = ref([]);

const options = ref([
  {
    value: "pie",
    label: i18n.global.t("form.statistics.pie")
  },
  {
    value: "bar",
    label: i18n.global.t("form.statistics.bar")
  },
  {
    value: "line",
    label: i18n.global.t("form.statistics.line")
  }
]);

const fields = ref([]);
const inputSearch = ref("");
const dataFilterDateRange = ref([]);
const dataFilterParams = ref({
  filter: {}
});
// 是否展开
const isExpand = ref(false);

onMounted(() => {
  getData();
  listFormFieldsRequest(route.query.key).then(res => {
    fields.value = res.data;
  });
});

const route = useRoute();

const handleFilter = () => {
  getData();
};

const handleReset = () => {
  inputSearch.value = "";
  dataFilterDateRange.value = [];
  dataFilterParams.value = {
    filter: {}
  };
};

const getData = () => {
  dataFilterParams.value.formKey = route.query.key;
  if (dataFilterDateRange.value && dataFilterDateRange.value.length) {
    dataFilterParams.value.beginDateTime = dataFilterDateRange.value[0];
    dataFilterParams.value.endDateTime = dataFilterDateRange.value[1];
  }
  dataFilterParams.value.filter.keyword = inputSearch.value;
  getFormAnalysisRequest(dataFilterParams.value).then(res => {
    list.value = res.data;
  });
};

const getCharData = data => {
  const config = cloneDeep(chartOptionMap[data.chartType]);
  // 柱状 折现图
  if (["bar", "line"].includes(data.chartType)) {
    if (!data.multiCategory) {
      config.xAxis.data = Object.keys(data.optionDataMap) || [];
      config.series[0].data = Object.values(data.optionDataMap).map(item => item.value) || [];
      config.series[0].type = data.chartType;
    } else {
      const optionConfig = transformToEchartsData(data.optionDataMap, config);
      config.xAxis.data = optionConfig.xAxis.data;
      config.series = optionConfig.series;
    }
  } else {
    // 如果是饼图，检查维度数量
    const dimensionCount = Object.keys(data.optionDataMap).length;
    if (dimensionCount > 3) {
      // 如果维度超过3个，自动切换到柱状图
      data.chartType = 'bar';
      return getCharData(data);
    }
    config.series[0].data = [];
    if (data.optionDataMap) {
      config.series[0].data = Object.values(data.optionDataMap).map(item => {
        return { name: item.label, value: item.value };
      });
    }
  }
  return config;
};

const transformToEchartsData = (data, optionConfig) => {
  // 初始化 x 轴类别（type 字段的所有唯一值）
  const xAxisData = Array.from(new Set(Object.values(data).map(item => item.type)));

  // 初始化 series 数据
  const seriesData = {};

  // 遍历输入数据，按 label 分类
  Object.values(data).forEach(item => {
    const label = item.label;
    const type = item.type;
    const value = item.value;

    // 如果 seriesData 还没有该 label，初始化它
    if (!seriesData[label]) {
      seriesData[label] = Array(xAxisData.length).fill(0); // 初始化为0的数组
    }

    // 在 seriesData 中填充对应 type 的值
    const index = xAxisData.indexOf(type);
    if (index !== -1) {
      seriesData[label][index] = value;
    }
  });

  // 将 seriesData 转换为 ECharts series 格式
  const series = Object.keys(seriesData).map(label => ({
    ...optionConfig.series[0],
    name: label,
    data: seriesData[label]
  }));

  // 返回 ECharts 的配置对象
  return {
    xAxis: {
      type: "category",
      data: xAxisData
    },
    series: series
  };
};

const getTableData = data => {
  let fieldName = Object.keys(data.optionDataMap) || [];
  let dataNum = Object.values(data.optionDataMap).map(item => item.value) || [];
  let sum = dataNum.reduce((a, b) => a + b, 0);
  return fieldName.map((field, index) => ({
    fieldName: field,
    data: dataNum[index],
    proportion: ((dataNum[index] / sum) * 100).toFixed(2) + "%"
  }));
};
</script>

<style lang="scss" scoped>
.analysis {
  width: 100%;
  padding: 20px;
  background-color: var(--el-bg-color-page);
  min-height: calc(100vh - 84px);

  .filter-wrap {
    background-color: var(--el-bg-color);
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

    .filter-title {
      font-size: 16px;
      font-weight: 500;
      color: var(--el-text-color-primary);
      margin-bottom: 15px;
      padding-bottom: 10px;
      border-bottom: 1px solid var(--el-border-color-lighter);
    }

    .filter-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;

      .left {
        display: flex;
        align-items: center;
      }

      .right {
        display: flex;
        align-items: center;
      }
    }
  }

  .chart-container {
    .chart-item {
      margin-bottom: 20px;

      .chart-card {
        border-radius: 8px;
        overflow: hidden;

        .title-wrap {
          padding: 15px;
          display: flex;
          align-items: center;
          justify-content: space-between;
          border-bottom: 1px solid var(--el-border-color-lighter);
        }

        .title {
          font-size: 16px;
          font-weight: 500;
          color: var(--el-text-color-primary);
          display: flex;
          align-items: center;

          .question-number {
            background-color: var(--el-color-primary);
            color: white;
            padding: 2px 8px;
            border-radius: 4px;
            margin-right: 8px;
            font-size: 14px;
            font-weight: normal;
          }
        }

        .chart {
          height: 400px;
          padding: 20px;
        }

        .table-container {
          padding: 20px;

          .analysis-table-title {
            font-size: 16px;
            font-weight: 500;
            color: var(--el-text-color-primary);
            margin-bottom: 15px;
          }
        }
      }
    }
  }
}

.chart-type-btn {
  height: 32px !important;
}
</style>
